package com.atguigu.eduucenter.service.impl;

import com.aiguigu.commonutils.JwtUtils;
import com.aiguigu.commonutils.MD5;
import com.aiguigu.commonutils.R;
import com.aiguigu.commonutils.ResultCode;
import com.atguigu.eduucenter.entity.UcenterMember;
import com.atguigu.eduucenter.entity.vo.RegisterUserVo;
import com.atguigu.eduucenter.mapper.UcenterMemberMapper;
import com.atguigu.eduucenter.service.UcenterMemberService;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author Y丶HS练习谷粒商城
 * @since 2022-10-06
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Resource
    private RedisTemplate redisTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String login(UcenterMember entity) {
        String mobile = entity.getMobile();
        String password = entity.getPassword();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new GuLiException(R.error().getCode(), "手机号或者密码为空");
        }
        // 判断手机号是否正确
        LambdaQueryWrapper<UcenterMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UcenterMember::getMobile, mobile);
        UcenterMember ucenterMember = baseMapper.selectOne(queryWrapper);
        if (Objects.isNull(ucenterMember)) {
            throw new GuLiException(R.error().getCode(), "手机号不存在");
        }
        // 判断密码是否正确 注意：需要加密
        password = MD5.encrypt(password);
        if (!password.equals(ucenterMember.getPassword())) {
            throw new GuLiException(R.error().getCode(), "密码错误");
        }
        // 是否被禁用
        if (ucenterMember.getIsDisabled()) {
            throw new GuLiException(R.error().getCode(), "用户被禁用");
        }
        // 未加密token
        String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
        String encrypt = MD5.encrypt(jwtToken);
        redisTemplate.opsForValue().set(encrypt, jwtToken, 15, TimeUnit.MINUTES);
        logger.info("登录成功,token:{}", jwtToken);
        // 加密的token
        return encrypt;
    }

    @Override
    public void register(RegisterUserVo entity) {

        String code = entity.getCode();

        String nickname = entity.getNickname();
        String mobile = entity.getMobile();
        String password = entity.getPassword();
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(code) || StringUtils.isEmpty(nickname)
        ) {
            throw new GuLiException(R.error().getCode(), "必填数据为空为空");
        }
        // 判断验证码是否为空
        String redisCode = (String) redisTemplate.opsForValue().get("api:sms:code:" + mobile);
        if (!code.equals(redisCode)) {
            throw new GuLiException(ResultCode.ERROR, "验证码错误或已经失效");
        }

        if (this.isExist(mobile)) {
            throw new GuLiException(ResultCode.ERROR, "手机号已经被注册");
        }
        password = MD5.encrypt(password);
        UcenterMember ucenterMember = new UcenterMember();
        ucenterMember.setMobile(mobile);
        ucenterMember.setPassword(password);
        ucenterMember.setNickname(entity.getNickname());
        ucenterMember.setIsDisabled(false);
        this.save(ucenterMember);
    }

    @Override
    public Boolean isExist(String mobile) {
        int count = this
                .count(
                        new LambdaQueryWrapper<UcenterMember>()
                                .eq(UcenterMember::getMobile, mobile)
                );
        return count > 0;
    }

    @Override
    public UcenterMember getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("token");
        // 判断验证码是否为空
        String redisToken = (String) redisTemplate.opsForValue().get(token);
        String userId = JwtUtils.getIdByToken(redisToken);
        return this.getById(userId);
    }

    @Override
    public void logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
        } else {
            String redisToken = (String) redisTemplate.opsForValue().get(token);
            if (StringUtils.isEmpty(redisToken)) {
                return;
            }
            redisTemplate.delete(token);
        }


    }

    @Override
    public UcenterMember getByOpenid(String openid) {
        return this.getOne(
                new LambdaQueryWrapper<UcenterMember>().eq(UcenterMember::getOpenid, openid)
        );
    }

    @Override
    public String weiXinLogin(UcenterMember ucenterMember) {

        Boolean isDisabled = ucenterMember.getIsDisabled();
        if (isDisabled) {
            throw new GuLiException(ResultCode.ERROR, "用户被禁用");
        }

        // 未加密token
        String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());
        String encrypt = MD5.encrypt(jwtToken);
        redisTemplate.opsForValue().set(encrypt, jwtToken, 15, TimeUnit.MINUTES);
        logger.info("微信登录成功,token:{}", jwtToken);
        // 加密的token
        return encrypt;
    }

    @Override
    public Integer countRegister(String day) {
        return baseMapper.countRegister(day);
    }

}
